<?php
namespace frontend\controllers;
// header("Access-Control-Allow-Origin:http://medicals.qingguo188.com");
// header("Access-Control-Allow-Origin:http://localhost:8080");
// header("Access-Control-Allow-Methods:POST,GET");
// header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
// header("Access-Control-Allow-Credentials: true");
use common\models\User;
use common\models\UserCode;
use common\models\UserSecondary;
use common\models\UserSignin;
use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
/**
 * User controller
 */
class BaseController extends Controller
{
  public function beforeAction($action)
  {
    $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
    $allow_origin = ['http://medicals.qingguo188.com', 'http://localhost:8080'];
    if(in_array($origin, $allow_origin)){
        header('Access-Control-Allow-Origin:'.$origin);
        header("Access-Control-Allow-Methods:POST,GET");
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        header("Access-Control-Allow-Credentials: true");
    }
    $session = Yii::$app->session;
    $session->open();
    if (!!$session->has('user_id')) {
      if ($session->has('user_level') == 1) {
        $User = new User();
        $userInfo = $User::find()->where(["id" => $session['user_id'],'status'=>1])->one();
        $now_time =  time();
        $old_time = strtotime($userInfo->last_operation_time);
        $differ_time = $now_time - $old_time;
        if($differ_time > $session->timeout && $userInfo->is_login == 1){
            return true;
        }
        if (!!$session['session_id'] && $session['session_id'] == $userInfo->session_id) {
          $userInfo->last_operation_time = date('Y-m-d H:i:s', strtotime('now'));
          $userInfo->update(false);
          return true;
        }
        return true;
      }
      if ($session->has('user_level') == 2) {
        $Secondary = new UserSecondary;
        $usersecond = $Secondary::find()->where(["id" => $session['user_id'],'status'=>1])->one();
        $now_time =  time();
        $old_time = strtotime($usersecond->last_operation_time);
        $differ_time = $now_time - $old_time;
        if($differ_time > $session->timeout && $usersecond->is_login == 1){
            return true;
        }
        if (!!$session['session_id'] && $session['session_id'] == $usersecond->session_id) {
          $usersecond->last_operation_time = date('Y-m-d H:i:s', strtotime('now'));
          $usersecond->update(false);
          return true;
        }
        return true;
      }
    }
    return true;
  }
}